/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2023-2023. All rights reserved.
 *
 */

import { spawnSync, SpawnSyncOptionsWithBufferEncoding } from 'child_process';
import fs from 'fs';
import fse from 'fs-extra';
import path from 'path';
import process from 'process';

import { HvigorLogger } from '../../base/log/hvigor-log.js';
import { DEFAULT_HVIGOR_CONFIG_JSON_FILE_NAME, PROJECT_CACHES, WORK_SPACE } from '../../common/const/const.js';
import { HVIGOR_PROJECT_WRAPPER_HOME } from '../../common/const/path-const.js';
import { HvigorConfigJson } from '../../common/type.js';
import { hash } from '@ohos/hvigor-common';
import { getHvigorUserHomeCacheDir } from '../../common/util/hvigor-user-home.js';
import { parseJsonFile } from '../../common/util/parse-json/parse-json-util.js';

const _log: HvigorLogger = HvigorLogger.getLogger('hvigor');

/**
 * 通过node原生require.resolve接口方法来判断在指定的paths路径中是否可以找到对应的npm包
 *
 * @param {string} packName npm pack name
 * @param {string[]} nodePaths node paths
 * @returns {boolean} true/false
 */
export function hasNpmPackInPaths(packName: string, nodePaths: string[]): boolean {
  try {
    require.resolve(packName, { paths: [...nodePaths] });
    return true;
  } catch (e) {
    return false;
  }
}

export function executeCommand(command: string, parameters: string[], options: SpawnSyncOptionsWithBufferEncoding, hvigorProjectDependenciesHome: string) {
  const executeResult = spawnSync(command, parameters, options);

  if (executeResult.status !== 0) {
    _log.error(`${command} execute failed.`);
    try {
      fse.removeSync(hvigorProjectDependenciesHome);
    } catch (e) {
      _log.error(`Deleting the directory ${hvigorProjectDependenciesHome} failed. Please try delete and execute again`);
    }
    process.exit(-1);
  }
}

export function getHvigorProjectHome() {
  const hvigorProjectHome = path.resolve(getHvigorUserHomeCacheDir(), PROJECT_CACHES, hash(path.resolve(process.cwd())), WORK_SPACE);
  process.env['WORKSPACE_DIR'] = hvigorProjectHome;
  return hvigorProjectHome;
}

export function getCurrentProjectCacheDirHash() {
  return hash(process.env.NODE_PATH ?? '');
}

function readProjectHvigorConfig(): HvigorConfigJson {
  const hvigorConfigJsonPath = path.resolve(HVIGOR_PROJECT_WRAPPER_HOME, DEFAULT_HVIGOR_CONFIG_JSON_FILE_NAME);

  // hvigorw端强依赖此文件，hvigor-config.json5不存在则报错
  if (!fs.existsSync(hvigorConfigJsonPath)) {
    _log.printErrorExit('HVIGOR_CONFIG_NOT_EXIST', [hvigorConfigJsonPath]);
  }
  const json = parseJsonFile(hvigorConfigJsonPath) as HvigorConfigJson;
  json.dependencies = json.dependencies ?? {};
  delete json.dependencies['@ohos/hvigor'];
  delete json.dependencies['@ohos/hvigor-ohos-plugin'];
  return json;
}
